import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
 
 
class QRatioButtonDemo(QWidget):
    def __init__(self):
        super(QRatioButtonDemo, self).__init__()
        self.initUI()
 
 
    def initUI(self):
        self.setWindowTitle('QRatioButton')
        self.resize(350,100)
        #水平布局
        layout=QHBoxLayout()
 
        self.btn1=QRadioButton('单选按钮1')
        # 设为默认是选中状态
        self.btn1.setChecked(True)
        #toggled是状态切换的信号
        self.btn1.toggled.connect(self.buttonState)
        layout.addWidget(self.btn1)
 
        self.btn2=QRadioButton('单选按钮2')
        self.btn2.toggled.connect(self.buttonState)
        layout.addWidget(self.btn2)
 
        self.setLayout(layout)
 
 
    def buttonState(self):
        ratiobtn=self.sender()
        if ratiobtn.isChecked() == True:
            print('<' + ratiobtn.text() + '>被选中')
        else:
            print('<' + ratiobtn.text() + '>被取消选中状态')
        #同意容器下单选按钮是互斥的，所以不必利用ratiobtn.text()来分情况判断
        '''
        if ratiobtn.text()=='单选按钮1':
            #是否被选中
            if ratiobtn.isChecked()==True:
                print('<'+ratiobtn.text()+'>被选中')
            else:
                print('<'+ratiobtn.text()+'>被取消选中状态')
        if ratiobtn.text()=='单选按钮2':
            if ratiobtn.isChecked()==True:
                print('<'+ratiobtn.text()+'>被选中')
            else:
                print('<'+ratiobtn.text()+'>被取消选中状态')
        '''
 
 
if __name__=='__main__':
    app=QApplication(sys.argv)
    main=QRatioButtonDemo()
    main.show()
    sys.exit(app.exec_())
 
 
